package com.qdlc.p2p.manage.action.additional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.FinanFlowQueryService;
import com.qdlc.p2p.biz.service.FinanFlowService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.AdditionalFlowUploadType;
import com.qdlc.p2p.common.constant.BorrowUploadType;
import com.qdlc.p2p.common.constant.RealNameStatus;
import com.qdlc.p2p.common.constant.UserType;
import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.FinanFlowExecption;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.AdditionalFlowInvestor;
import com.qdlc.p2p.dal.dto.AdditionalFlowProject;
import com.qdlc.p2p.dal.dto.AdditionalFlowRepayPlan;
import com.qdlc.p2p.dal.dto.AdditionalFlowUpload;
import com.qdlc.p2p.dal.dto.BorrowUpload;
import com.qdlc.p2p.dal.dto.Operator;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserCache;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.FlowProjectModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 后台管理理财项目action
 * @author wjx
 * @version 2.0
 * @date 2015年5月18日 下午4:42:01
 */
public class ManageFlowAction extends BaseAction<FlowProjectModel> implements ModelDriven<FlowProjectModel> {
	
	private static Logger logger = Logger.getLogger(ManageFlowAction.class);
	
	@Resource
	private FinanFlowQueryService finanFlowQueryService;
	
	@Resource
	private FinanFlowService finanFlowService;
	@Resource
	private UserService userService;
	
	private Map<String, Object> data;
	
	@Resource
	private UserIdentifyService userIdentifyService;
	/**
	 * 跳转理财项目列表
	 * @return
	 */
	@Action("/modules/additional/finanFlow/flowManage")
	public String flowManage(){
		return "flowManage";
	}
	
	
	@Action("/modules/additional/finanFlow/flowProjectJson")
	public void flowProjectJson() throws IOException{
		data = new HashMap<String, Object>();
		PageDataList<FlowProjectModel> pageList = finanFlowQueryService.getPageFlowProject(model);
		int total = pageList.getPage().getTotal();
		data.put("total", total);
		data.put("rows", pageList.getList());
		printJson(getStringOfJpaObj(data));
	}
	
	
	@Action("/modules/additional/finanFlow/addFlowPage")
	public String addFlowPage(){
		saveToken("addFlowToken");
		return "addFlowPage";
	}
	
	/**
	 * <p>新增流转标</p>
	 * @author 原系统 2016年2月4日 下午4:55:43
	 * @throws IOException
	 * @modificationHistory=========================逻辑或功能性重大变更记录
	 * @modify by user: Kaiju Zhao 2016年2月4日 下午4:55:43
	 * @modify by reason: 消除报错和规范代码
	 */
	@Action("/modules/additional/finanFlow/doAddFlow")
	public void doAddFlow() throws IOException{
		checkToken("addFlowToken");
		model.checkAddFlowProject();
		User user = userService.getUserByEmail(model.getEmail());
		if (null == user) {
		    throw new FinanFlowExecption(MessageUtil.getMessage("MF103001007"),BusinessException.TYPE_JSON);
        }
		UserCache userCache = UserUtils.getUserCacheByUserId(user);
		if (null == userCache
		        || UserType.INVESTOR == userCache.getUserType()) {
		    throw new FinanFlowExecption(MessageUtil.getMessage("MF103001007"),BusinessException.TYPE_JSON);
        }
		UserIdentify ui = userIdentifyService.getUserIdentifyByUserId(user.getUserId());
		String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
		if (RealNameStatus.AUTHENTICATED_PASS != ui.getRealNameStatus()
		        || StringUtil.isBlank(tppUserCustId)) {
			throw new UserException(MessageUtil.getMessage("MF103001008"), BusinessException.TYPE_JSON); 
		}
		List<AdditionalFlowUpload> list = new ArrayList<AdditionalFlowUpload>();
		String[] picPaths = request.getParameterValues("picPath");
		if (picPaths == null) {
			throw new BorrowException("图片不能为空", BusinessException.TYPE_JSON);
		}
		for (String picPath : picPaths) {
			AdditionalFlowUpload bu = new AdditionalFlowUpload();
			bu.setPicPath(picPath);
			bu.setType(AdditionalFlowUploadType.FLOW_DATA);
			list.add(bu);
		}

		String[] thumbnailPaths = request.getParameterValues("thumbnailPicPath");
		if (null != thumbnailPaths
				&& thumbnailPaths.length > 0) {
			for (String picPath : thumbnailPaths) {
				AdditionalFlowUpload bu = new AdditionalFlowUpload();
				bu.setPicPath(picPath);
				bu.setType(AdditionalFlowUploadType.THUMBNAIL);
				list.add(bu);
			}
		}
		
		/*String remark = paramString("content");
		model.setRemark(remark);*/
		finanFlowService.addFlowProject(model,user,list);
		printResult(MessageUtil.getMessage("MS103005001"), true);
	}
	
	/**
	 * 跳转审核页面
	 * @return
	 */
	@Action("/modules/additional/finanFlow/verifyFlowPage")
	public String verifyFlowPage(){
		long id = paramLong("id");
		AdditionalFlowProject project  = finanFlowQueryService.getFlowProjectById(id);
		if (null ==project || project.getStatus() !=FlowProjectModel.PROJECT_ADD_STATUS) {
			logger.info("该项目不能进行审核操作，id："+id);
			throw new FinanFlowExecption(MessageUtil.getMessage("MF103006001"));
		}
		FlowProjectModel model = FlowProjectModel.instance(project);
		model.setUserName(project.getUser().getUserName());
		request.setAttribute("project", model);
		return "verifyFlowPage";
	}
	
	
	/**
	 * 处理审核方法
	 * @throws IOException 
	 */
	@Action("/modules/additional/finanFlow/doVerifyFlowProject")
	public void doVerifyFlowProject() throws IOException{
		AdditionalFlowProject project  = finanFlowQueryService.getFlowProjectById(model.getId());
		if (null ==project || project.getStatus()!=FlowProjectModel.PROJECT_ADD_STATUS) {
			throw new FinanFlowExecption(MessageUtil.getMessage("MF103006001"));
		}
		Operator operator = this.getOperator();
		model.setOperator(operator);
		finanFlowService.verifyFlowProject(model);
		printWebSuccess();
	}
	
	/**
	 * 项目查看详情
	 * @return
	 */
	@Action("/modules/additional/finanFlow/viewFlowProject")
	public String viewFlowProject(){
		long id = paramLong("id");
		AdditionalFlowProject project  = finanFlowQueryService.getFlowProjectById(id);
		if (null == project) {
			throw new FinanFlowExecption(MessageUtil.getMessage("MF103006001"));
		}
		FlowProjectModel model = FlowProjectModel.instance(project);
		model.setUserName(project.getUser().getUserName());
		request.setAttribute("project", model);
		List<AdditionalFlowInvestor> list = finanFlowQueryService.getFlowInvestor(id);
		request.setAttribute("list", list);
		return "viewFlowProject";
	}
	
	
	/**
	 * 查看还款计划
	 * @return
	 */
	@Action("/modules/additional/finanFlow/viewFlowRepayPlan")
	public String viewFlowRepayPlan(){
		long id = paramLong("id");
		AdditionalFlowProject project  = finanFlowQueryService.getFlowProjectById(id);
		FlowProjectModel model = FlowProjectModel.instance(project);
		model.setUserName(project.getUser().getUserName());
		List<AdditionalFlowRepayPlan> repayList = finanFlowQueryService.getFlowRepayPlanList(id);
		request.setAttribute("list", repayList);
		request.setAttribute("project", model);
		return "viewFlowRepayPlan";
		
	}
	
	

}
